package com.heisen.feignClient.configure;

import com.heisen.base.utils.GateWayConstantUtils;
import com.heisen.feignClient.factory.InfoFeignLoggerFactory;
import feign.Logger;
import feign.RequestInterceptor;
import org.springframework.cloud.openfeign.FeignLoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.util.Base64Utils;

/**
 * @author sen
 * @description
 * @date 2023/12/18 18:05
 */

public class XmOAuth2FeignConfigure   {


    @Bean
    public RequestInterceptor oauth2FeignRequestInterceptor() {
        return requestTemplate -> {
            SecurityContext context = SecurityContextHolder.getContext();
            Authentication authentication = context.getAuthentication();
            if(authentication != null){
                Object details = authentication.getDetails();
                if (details instanceof OAuth2AuthenticationDetails) {
                    String authorizationToken = ((OAuth2AuthenticationDetails) details).getTokenValue();
                    requestTemplate.header(HttpHeaders.AUTHORIZATION, "bearer " + authorizationToken);
                }

            }


            // 添加 Zuul Token
            String zuulToken = new String(Base64Utils.encode(GateWayConstantUtils.ZUUL_TOKEN_VALUE.getBytes()));
            requestTemplate.header(GateWayConstantUtils.ZUUL_TOKEN_HEADER, zuulToken);

        };
    }


    /**
     *  fengin  日志功能 bean
     * @return
     */
    @Bean
    Logger.Level feignLevel() {
        return Logger.Level.FULL;
    }

    @Bean
    FeignLoggerFactory infoFeignLoggerFactory() {
        return new InfoFeignLoggerFactory();

    }
}
